package org.jeecg.modules.extbpm.process.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.extbpm.process.entity.ExtActProcessForm;
import org.jeecg.modules.extbpm.process.service.IExtActProcessFormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import lombok.extern.slf4j.Slf4j;

 /**
 * @Title: Controller
 * @Description: 流程业务关联表
 * @author： jeecg-boot
 * @date：   2019-03-15
 * @version： V1.0
 */
@RestController("extActProcessFormController")
@RequestMapping("/act/process/extActProcessForm")
@Slf4j
public class ExtActProcessFormController {
	@Autowired
	private IExtActProcessFormService extActProcessFormService;
	
	/**
	  * 分页列表查询
	 * @param extActProcessForm
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<ExtActProcessForm>> queryPageList(ExtActProcessForm extActProcessForm,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<ExtActProcessForm>> result = new Result<IPage<ExtActProcessForm>>();
		QueryWrapper<ExtActProcessForm> queryWrapper = new QueryWrapper<ExtActProcessForm>(extActProcessForm);
		Page<ExtActProcessForm> page = new Page<ExtActProcessForm>(pageNo,pageSize);
		//排序逻辑 处理
		String column = req.getParameter("column");
		String order = req.getParameter("order");
		if(oConvertUtils.isNotEmpty(column) && oConvertUtils.isNotEmpty(order)) {
			if("asc".equals(order)) {
				queryWrapper.orderByAsc(oConvertUtils.camelToUnderline(column));
			}else {
				queryWrapper.orderByDesc(oConvertUtils.camelToUnderline(column));
			}
		}
		IPage<ExtActProcessForm> pageList = extActProcessFormService.page(page, queryWrapper);
		//log.debug("查询当前页："+pageList.getCurrent());
		//log.debug("查询当前页数量："+pageList.getSize());
		//log.debug("查询结果数量："+pageList.getRecords().size());
		//log.debug("数据总数："+pageList.getTotal());
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param extActProcessForm
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<ExtActProcessForm> add(@RequestBody ExtActProcessForm extActProcessForm) {
		Result<ExtActProcessForm> result = new Result<ExtActProcessForm>();
		try {
			extActProcessFormService.save(extActProcessForm);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败:编码重复或者改表名已配置");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param extActProcessForm
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<ExtActProcessForm> edit(@RequestBody ExtActProcessForm extActProcessForm) {
		Result<ExtActProcessForm> result = new Result<ExtActProcessForm>();
		ExtActProcessForm extActProcessFormEntity = extActProcessFormService.getById(extActProcessForm.getId());
		if(extActProcessFormEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = extActProcessFormService.updateById(extActProcessForm);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<ExtActProcessForm> delete(@RequestParam(name="id",required=true) String id) {
		Result<ExtActProcessForm> result = new Result<ExtActProcessForm>();
		ExtActProcessForm extActProcessForm = extActProcessFormService.getById(id);
		if(extActProcessForm==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = extActProcessFormService.removeById(id);
			if(ok) {
				result.success("删除成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<ExtActProcessForm> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<ExtActProcessForm> result = new Result<ExtActProcessForm>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.extActProcessFormService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<ExtActProcessForm> queryById(@RequestParam(name="id",required=true) String id) {
		Result<ExtActProcessForm> result = new Result<ExtActProcessForm>();
		ExtActProcessForm extActProcessForm = extActProcessFormService.getById(id);
		if(extActProcessForm==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(extActProcessForm);
			result.setSuccess(true);
		}
		return result;
	}
	
	/**
	  * 通过生成默认编码
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/genDefaultCode")
	public Result<String> genDefaultCode(@RequestParam(name="tabeName",required=true) String tabeName) {
		Result<String> result = new Result<String>();
		LambdaQueryWrapper<ExtActProcessForm> queryWrapper = new LambdaQueryWrapper<ExtActProcessForm>();
		String value = "dev_"+tabeName+"_";
		queryWrapper.likeRight(ExtActProcessForm::getRelationCode,value);
		queryWrapper.orderByDesc(ExtActProcessForm::getRelationCode);
		List<ExtActProcessForm> list = extActProcessFormService.list(queryWrapper);
		if(list==null||list.size()<=0) {
			String code = value+"001";
			result.setResult(code);
		}else {
			ExtActProcessForm extActProcessForm = list.get(0);
			String code = getMaxCode(value,extActProcessForm.getRelationCode());
			result.setResult(code);
			result.setSuccess(true);
		}
		return result;
	}
	
	private String getMaxCode(String pre,String code) {
		String defautCode = "001";
		try {
			Integer  seq = Integer.parseInt(code.substring(pre.length()));
			log.info("-------------------"+seq);
			defautCode = getNextStrNum(seq);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return pre+defautCode;
	}
	
	/**
	 * 将数字前面位数补零
	 * 
	 * @param num
	 * @return
	 */
	private static String getNextStrNum(int num) {
		return getStrNum(getNextNum(num));
	}

	/**
	 * 将数字前面位数补零
	 * 
	 * @param num
	 * @return
	 */
	private static String getStrNum(int num) {
		String s = String.format("%0" + 3 + "d", num);
		return s;
	}
	/**
	 * 递增获取下个数字
	 * 
	 * @param num
	 * @return
	 */
	private static int getNextNum(int num) {
		num++;
		return num;
	}
	
	/**
	  * 通过processId查询
	 * @param processId
	 * @return
	 */
	@GetMapping(value = "/queryFormBizCodeByProcessid")
	public Result<List<ExtActProcessForm>> queryFormBizCodeByProcessid(@RequestParam(name="processId",required=true) String processId,@RequestParam(name="formType",required=true) String formType) {
		Result<List<ExtActProcessForm>> result = new Result<List<ExtActProcessForm>>();
		QueryWrapper<ExtActProcessForm> queryWrapper = new QueryWrapper<ExtActProcessForm>(); 
		queryWrapper.lambda().eq(ExtActProcessForm::getProcessId, processId);
		queryWrapper.lambda().eq(ExtActProcessForm::getFormType, formType);
		List<ExtActProcessForm> list = extActProcessFormService.list(queryWrapper);
		if(list==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(list);
			result.setSuccess(true);
		}
		return result;
	}
	
	/**
	  * 通过processId查询
	 * @param processId
	 * @return
	 */
	@GetMapping(value = "/queryFormTypeByProcessid")
	public Result<List<String>> queryFormTypeByProcessid(@RequestParam(name="processId",required=true) String processId) {
		Result<List<String>> result = new Result<List<String>>();
		List<String> list = extActProcessFormService.queryFormTypeByProcessid(processId);
		if(list==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(list);
			result.setSuccess(true);
		}
		return result;
	}

	
	/**
	  * 通过processId查询
	 * @param processId
	 * @return
	 */
	@GetMapping(value = "/queryFieldByOnlineCode")
	public Result<List<Map<String,String>>> queryFieldByOnlineCode(@RequestParam(name="tableName",required=true) String tableName) {
		Result<List<Map<String,String>>> result = new Result<List<Map<String,String>>>();
		List<Map<String,String>> list = extActProcessFormService.queryFieldByOnlineCode(tableName);
		if(list==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(list);
			result.setSuccess(true);
		}
		return result;
	}
}
